package cn.javaSong.utils;

import cn.hutool.core.lang.Snowflake;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.util.*;

/**
 * 字符串工具类
 *
 * @author
 */
public class StringUtil {
    public static void main(String[] args) {
        String kai = "你好-世界";
        System.out.println(StringUtil.toPinyin(kai));
    }

    /**
     * 判断是否是空
     * @param str
     * @return
     */
    public static boolean isEmpty(String str) {
        if (str == null || "".equals(str.trim())) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 根据图片的id及路径删除图片
     * @param folderPath
     * @param fileName
     */
    public void deleteFileByName(String folderPath, String fileName) {
        Path directory = Paths.get(folderPath);
        try {
            Files.list(directory)
                    .filter(path -> path.getFileName().toString().equals(fileName))
                    .forEach(path -> {
                        try {
                            Files.delete(path);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String toPinyin(String chinese) {
        StringBuilder pinyin = new StringBuilder();
        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        format.setVCharType(HanyuPinyinVCharType.WITH_V);

        char[] input = chinese.toCharArray();
        try {
            for (char c : input) {
                if (Character.toString(c).matches("[\\u4E00-\\u9FA5]+")) { // 判断是否是中文字符
                    String[] temp = PinyinHelper.toHanyuPinyinStringArray(c, format);
                    if (temp != null) {
                        pinyin.append(temp[0]);
                    } else {
                        pinyin.append(c); // 如果不是中文字符，则原样保留
                    }
                } else {
                    pinyin.append(c); // 非中文字符，如"-"等，原样保留
                }
            }
        } catch (BadHanyuPinyinOutputFormatCombination badHanyuPinyinOutputFormatCombination) {
            badHanyuPinyinOutputFormatCombination.printStackTrace();
        }
        return pinyin.toString();
    }

    public static boolean isEmptys(Collection coll) {
        return (coll == null || coll.isEmpty());
    }

    /**
     * 判断是否不是空
     * @param str
     * @return
     */
    public static boolean isNotEmpty(String str) {
        if ((str != null) && !"".equals(str.trim())) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 格式化模糊查询
     * @param str
     * @return
     */
    public static String formatLike(String str) {
        if (isNotEmpty(str)) {
            return "%" + str + "%";
        } else {
            return null;
        }
    }

    /**
     * 过滤掉集合里的空格
     * @param list
     * @return
     */
    public static List<String> filterWhite(List<String> list) {
        List<String> resultList = new ArrayList<String>();
        for (String l : list) {
            if (isNotEmpty(l)) {
                resultList.add(l);
            }
        }
        return resultList;
    }

    /**
     * 获取当前时间戳
     * @return
     */
    public static String getCurrentDateStr() {
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmssSSSSSSSSS");
        return sdf.format(date);
    }

    /**
     * 封装mp3下载保存
     * @param mp3Url
     * @param destinationPath
     * @throws IOException
     */
    public static void downloadMp3(String mp3Url, String destinationPath) throws IOException {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpGet httpGet = new HttpGet(mp3Url);
            try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
                byte[] fileBytes = EntityUtils.toByteArray(response.getEntity());
                Path path = Paths.get(destinationPath);
                Files.write(path, fileBytes);
            }
        }
    }

    /**
     * 获取毫秒级时间戳
     * @return
     */
    public static String timestampMillis() {
        // 获取当前时间的Instant对象，Instant类提供了访问纳秒级时间的支持
        Instant now = Instant.now();
        // 转换为毫秒级别的时间戳
        long timestampMillis = now.toEpochMilli();
        // 使用SimpleDateFormat格式化为18位的时间戳字符串，格式为yyyyMMddHHmmssSSSS
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddMHHmmssSSSS");
        return sdf.format(timestampMillis);
    }

    /**
     * 雪花算法生成18位随机数
     * @return
     */
    public static Long snowflakeMillis() {
        Snowflake companyId = cn.hutool.core.util.IdUtil.createSnowflake(3, 1);
        return companyId.nextId();
    }

    /**
     * 去除html标签
     */
    public static String stripHtml(String content) {
        // <p>段落替换为换行
        content = content.replaceAll("<p .*?>", "\r\n");
        // <br><br/>替换为换行
        content = content.replaceAll("<br\\s*/?>", "\r\n");
        // 去掉其它的<>之间的东西
        content = content.replaceAll("\\<.*?>", "");
        // 去掉空格
        content = content.replaceAll(" ", "");
        return content;
    }

    /**
     * 生成六位随机数
     *
     * @return
     */
    public static String genSixRandomNum() {
        Random random = new Random();
        String result = "";
        for (int i = 0; i < 6; i++) {
            result += random.nextInt(10);
        }
        return result;
    }

    /**
     * 生成由[A-Z,0-9]生成的随机字符串
     * @param length 欲生成的字符串长度
     * @return
     */
    public static String getRandomString(int length) {
        Random random = new Random();

        StringBuffer sb = new StringBuffer();

        for (int i = 0; i < length; ++i) {
            int number = random.nextInt(2);
            long result = 0;

            switch (number) {
                case 0:
                    result = Math.round(Math.random() * 25 + 65);
                    sb.append(String.valueOf((char) result));
                    break;
                case 1:

                    sb.append(String.valueOf(new Random().nextInt(10)));
                    break;
            }
        }
        return sb.toString();
    }

    /**
     * 生成随机字符串
     * @return
     */
    public static String createUUID(){
        return String.valueOf(UUID.randomUUID()).replaceAll("-","");
    }


    public static String toUnderScoreCase(String s) {
        if (s == null) {
            return null;
        } else {
            StringBuilder sb = new StringBuilder();
            boolean upperCase = false;

            for(int i = 0; i < s.length(); ++i) {
                char c = s.charAt(i);
                boolean nextUpperCase = true;
                if (i < s.length() - 1) {
                    nextUpperCase = Character.isUpperCase(s.charAt(i + 1));
                }

                if (i > 0 && Character.isUpperCase(c)) {
                    if (!upperCase || !nextUpperCase) {
                        sb.append('_');
                    }

                    upperCase = true;
                } else {
                    upperCase = false;
                }

                sb.append(Character.toLowerCase(c));
            }

            return sb.toString();
        }
    }
}
